package com.sen.common.tenant.config;

import cn.hutool.core.util.StrUtil;
import com.sen.common.common.constrant.CommonConstrant;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 基础信息过滤器
 * @author esjiang
 */
@ConditionalOnClass(Filter.class)
public class TenantFilter extends OncePerRequestFilter {
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
                                    FilterChain filterChain) throws IOException, ServletException {
        try {
            String tenantId = request.getParameter(CommonConstrant.X_TENANT_HEADER);
            if (StrUtil.isBlank(tenantId)) {
                tenantId = request.getHeader(CommonConstrant.X_TENANT_HEADER);
            }
            if (StrUtil.isNotBlank(tenantId)) {
                TenantContextHolder.setTenant(tenantId);
            }
            filterChain.doFilter(request, response);
        } finally {
            TenantContextHolder.clear();
        }
    }


}
